import { defineStore } from 'pinia'
import { login, logout, getInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import defAva from '@/assets/mdImg/vue.svg'

const useUserStore = defineStore(
  'user',
  {
    state: () => ({
      token: getToken(),
      id: '',
      name: '',
      avatar: '',
      roles: [],
      permissions: []
    }),
    actions: {
      // 登录
      login(userInfo: { username: string; password: any; code: any; uuid: any }) {
        const username = userInfo.username.trim()
        const password = userInfo.password
        const code = userInfo.code
        const uuid = userInfo.uuid
        return new Promise<void>((resolve, reject) => {
          login(username, password, code, uuid).then(res => {
            let data = res as unknown as { token: string }
            setToken(data.token)
            this.token = data.token
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 获取用户信息
      getInfo() {
        return new Promise((resolve, reject) => {
          getInfo().then(res => {
            const user = res as unknown as {
                id: string
                userName: string
                userId: any
                avatar: string | null 
};
            const avatar = (user.avatar == "" || user.avatar == null) ? defAva : user.avatar;

            // if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
            //   this.roles = res.roles
            //   this.permissions = res.permissions
            // } else {
            //   this.roles = ['ROLE_DEFAULT']
            // }
            this.id = user.id
            this.name = user.userName
            this.avatar = avatar

            // 缓存用户信息
            // wflow 合并
            let userObj = {
                ...user,
                id: user.userId.toString(),
                name: user.userName,
                avatar: avatar,
                type: 'user', //固定值
            }
            localStorage.setItem('loginUser', JSON.stringify(userObj))
            // wflow 合并

            resolve(res)
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 退出系统
      logOut() {
        return new Promise<void>((resolve, reject) => {
          logout(this.token).then(() => {
            this.token = ''
            this.roles = []
            this.permissions = []
            removeToken()
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      }
    }
  })

export default useUserStore
